<template>
	<div>
		<div class="page-container">
			<el-form :model="dataForm" label-width="100px" :rules="dataFormRules" ref="dataForm" :size="size"
                label-position="right">
                <el-form-item label="ID" prop="id" v-if="false">
                    <el-input v-model="dataForm.id" :disabled="true" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="登录账号:" prop="hospitalAccount">
                    <el-input v-model="dataForm.hospitalAccount" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="登录密码:" prop="hospitalPassword">
                    <el-input v-model="dataForm.hospitalPassword" type="password" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="医院名称:" prop="hospitalName">
                    <el-input v-model="dataForm.hospitalName" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="负责人:" prop="hospitalPrincipal">
                    <el-input v-model="dataForm.hospitalPrincipal" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="联系方式:" prop="contactInformationfa">
                    <el-input v-model="dataForm.contactInformationfa" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="分润比例:" prop="dividedRatio">
                    <el-input v-model="dataForm.dividedRatio" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="精确位置:" prop="hospitalAddress">
                    <div id="all">
                        <el-input id="suggestId" name="hospitalAddress" placeholder="地址" v-model="dataForm.hospitalAddress" class="input_style"></el-input>
                        <div id="allmap"></div>
                    </div>
                </el-form-item>
                <el-form-item label="详细地址:" prop="hospitalAddressInfo">
                    <el-input v-model="dataForm.hospitalAddressInfo" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
			<div slot="footer" class="dialog-footer">
				<el-button :size="size" type="primary" @click.native="submitForm" :loading="editLoading">保存</el-button>
				<el-button :size="size" @click.native="dialogVisible = false">{{$t('action.cancel')}}</el-button>
			</div>
  		</div>
	</div>
  


</template>
<script>
import KtButton from "@/views/Core/KtButton"
import { format } from "@/utils/datetime"
import {MP} from "@/utils/map"


export default {
	data() {
		return {
            address_detail: null, //详细地址
            userlocation: {lng: "", lat: ""},
			size: 'small',
            hospital_id:'',
			filters: {
				name: ''
			},
			editLoading: false,
			dataFormRules: {
				hospitalAccount: [
					{ required: true, message: '请输入登录账号', trigger: 'blur' }
				],
                hospitalPassword: [
					{ required: true, message: '请输入登录密码', trigger: 'blur' }
				],
                hospitalName: [
					{ required: true, message: '请输入医院名称', trigger: 'blur' }
				],
                hospitalPrincipal: [
					{ required: true, message: '请输入负责人', trigger: 'blur' }
				],
                contactInformationfa: [
					{ required: true, message: '请输入联系方式', trigger: 'blur' }
				],
                dividedRatio: [
					{ required: true, message: '请输入分润比例', trigger: 'blur' }
				],
                hospitalAddress: [
					{ required: true, message: '请输入精确地址', trigger: 'blur' }
				],
                hospitalAddressInfo: [
					{ required: true, message: '请输入详细地址', trigger: 'blur' }
				],
			},
			// 新增编辑界面数据
			dataForm: {
                adminUserId:sessionStorage.getItem("userId"),//创建人id
				hospitalAccount: '',//登录账号
				hospitalPassword: '',//登录密码
				hospitalName: '',//医院名称
				hospitalPrincipal: '',//负责人
				contactInformationfa: '',//联系方式
				dividedRatio:0.00,//分润比例
                hospitalAddress:'',//精确地址
				hospitalAddressInfo: '',//详细地址
                hospitalLonHthree:'',//经度
                hospitalLatHthree:'',//纬度
                status:1,
			},
		}
	},
	methods: {
		// 编辑
		submitForm: function () {
                var me = this;
                debugger;
				this.$refs.dataForm.validate((valid) => {
				if (valid) {
					this.$confirm('确认提交吗？', '提示', {}).then(() => {
                        debugger;
						let params = this.dataForm;
                        if(me.hospital_id!=null && me.hospital_id !=''){
                            me.update()
                        }else{
                            me.add()
                        }
					})
				}
			})
		},
        //新增
        add(){
            let params = this.dataForm;
            console.log(params);
            debugger;
            this.$api.hospital.save(params).then((res) => {
                this.editLoading = false
                if(res.code == 200) {
                    sessionStorage.removeItem("hospital_id")
                    this.$message({ message: '操作成功', type: 'success' })
                    this.$refs['dataForm'].resetFields()
                } else {
                    sessionStorage.removeItem("hospital_id")
                    this.$message({message: '操作失败, ' + res.msg, type: 'error'})
                }
            })
        },
        //修改
        update(){
            debugger;
            let params = this.dataForm;
            console.log(params);
            this.$api.hospital.update(params).then((res) => {
                this.editLoading = false
                if(res.code == 200) {
                    this.$message({ message: '操作成功', type: 'success' })
                    this.$refs['dataForm'].resetFields()
                    sessionStorage.removeItem("hospital_id")
                } else {
                    sessionStorage.removeItem("hospital_id")
                    this.$message({message: '操作失败, ' + res.msg, type: 'error'})
                }
            })
        },
		// 时间格式化
      	dateFormat: function (row, column, cellValue, index){
          	return format(row[column.property])
      	},
        getid(){
            var me = this;
			me.hospital_id = sessionStorage.getItem("hospital_id");
            if(me.hospital_id !== '' && me.hospital_id !== null){
                let req = {"id":this.hospital_id}
                this.$api.hospital.findByid(req).then((res) => {
                    if(res.code != 200) {
                        this.$message({
                        message: res.msg,
                        type: 'error'
                        })
                    } else {
                        this.dataForm = res.hospital;
                    }
                })
            }
		},
        map(){
            this.$nextTick(function () {
          	MP("Vj2P3KUgAPeGoWjkwGz6qEPerVxzasX8").then( BMap => {
            var th = this
            var map = new BMap.Map("allmap");            // 创建Map实例
            var point = new BMap.Point(106.553, 29.569); // 创建点坐标
            map.centerAndZoom(point,15);
            map.enableScrollWheelZoom();
            var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
              {"input" : "suggestId"
              ,"location" : map
            })
            var myValue
            ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件
              var _value = e.item.value;
              myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
               th.dataForm.hospitalAddress = myValue
              setPlace();
            });
            function setPlace(){
              map.clearOverlays();    //清除地图上所有覆盖物
              function myFun(){
                th.userlocation = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
                map.centerAndZoom(th.userlocation, 18);
                map.addOverlay(new BMap.Marker(th.userlocation));    //添加标注
                debugger;
                console.log(th.userlocation.lng);
                console.log(th.userlocation.lat);
                th.dataForm.hospitalLonHthree = th.userlocation.lng;
                th.dataForm.hospitalLatHthree = th.userlocation.lat;
              }
              debugger;
              var local = new BMap.LocalSearch(map, { //智能搜索
                onSearchComplete: myFun
              });
              local.search(myValue);

			  //测试输出坐标（指的是输入框最后确定地点的经纬度）
				map.addEventListener("click",function(e){
                    debugger;
                    th.dataForm.hospitalLonHthree = th.userlocation.lng;
                    th.dataForm.hospitalLatHthree = th.userlocation.lat;
                    console.log(th.userlocation.lng);
                    console.log(th.userlocation.lat);
                    var geoc = new BMap.Geocoder();
                    var pt = e.point;
                    geoc.getLocation(pt,function(rs){
                        var addComp = rs.addressComponents;
                        th.dataForm.hospitalAddress = addComp.province+addComp.city+addComp.district+addComp.street+addComp.streetNumber;
                        //alert(th.dataForm.hospitalAddress);
                    })
				})
            }
            })
          })
        }
	},
    mounted() {
        this.map()
        this.getid()
	}
}
</script>

<style lang="scss" scoped>
    .page-container{
        width:40%;
        min-width:600px;
        margin:100px auto;
    }
	.page-editor{
		width:40%;
        min-width:600px;
		height:600px;
        margin:10px auto;
	}
    .el-button{
        width:150px;
        border-redius:5px;
        margin-left:50px;
    }
    .el-input {
        width: 300px;
        height: 32px;
        line-height: 32px;
    }
    .el-select {
        width: 300px;
    }
    #allmap{
        margin-top:10px;
        width: 300px;
        height: 200px;
        font-family: "微软雅黑";
        border:1px solid green;
    }
</style>